package com.lp.common.component;

import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-05-02 10:13:09
 */
@Service
public class RedisService {

    @Value("${cache.expiration}")
    private long expiration;

    @Autowired
    private StringRedisTemplate redis;

    public void put(String key, Object obj) {
//        redis.opsForValue().set(key, JSONUtil.toJsonStr(obj), expiration, TimeUnit.SECONDS);
        put(key, JSONUtil.toJsonStr(obj));
    }

    public void put(String key, Object obj, Long expiration) {
//        redis.opsForValue().set(key, JSONUtil.toJsonStr(obj), expiration, TimeUnit.SECONDS);
        put(key, JSONUtil.toJsonStr(obj), expiration);
    }

    public void put(String key, String obj) {
//        redis.opsForValue().set(key, obj, expiration, TimeUnit.SECONDS);
        put(key, obj, null);
    }

    public void put(String key, String obj, Long expiration) {
        if (expiration == null) {
            expiration = this.expiration;
        }
        redis.opsForValue().set(key, obj, expiration, TimeUnit.SECONDS);
    }

    public void delete(String key) {
        redis.delete(key);
    }

    public void delete(Collection<String> keys) {
        redis.delete(keys);
    }

    public String get(String key) {
        return redis.opsForValue().get(key);
    }

    public <T> T get(String key, Class<T> tClass) {
        String s = redis.opsForValue().get(key);
        T result = null;
        if (s != null) {
            result = JSONUtil.toBean(s, tClass);
        }
        return result;
    }

    public <T> List<T> getList(String key, Class<T> tClass) {
        String s = redis.opsForValue().get(key);
        List<T> result = new ArrayList<>(6);
        if (s != null) {
            result = JSONUtil.toList(JSONUtil.parseArray(s), tClass);
        }
        return result;
    }

    public void setExpiration(String key, Long expiration) {
        if (expiration == null) {
            expiration = this.expiration;
        }
        redis.expire(key, expiration, TimeUnit.SECONDS);
    }
}
